<template>
  <div class="category">
    <Breadcrumb></Breadcrumb>
    <div class="wrapper">
      <div class="title">产品类目管理</div>
      <div class="tree">
        <!-- 一级按钮 -->
        <el-button type="warning" style="margin-bottom:20px;" @click="addoneclass">新增一级导航类目</el-button>
        <el-tree style="max-width: 600px" :data="dataSource" show-checkbox node-key="id" default-expand-all
          :expand-on-click-node="false" :render-content="renderContent" />
      </div>
      <Dialog ref="centerDialog" :title="title" :type="type" :cid="cid" :id="dataid" @update_data="itemCategory">
      </Dialog>
    </div>
  </div>
</template>

<script setup>
import { ref,getCurrentInstance,reactive,onMounted } from 'vue';
import { Delete, Plus, Edit } from '@element-plus/icons-vue'
import Dialog from './Dialog/index.vue'
//全局导入
const cxt = getCurrentInstance()
const API = cxt.appContext.config.globalProperties.$API
// 定义 Tree 接口
class Tree {
  constructor(id, label, children, cid, type) {
    this.id = id;
    this.label = label;
    this.children = children || [];
    this.cid = cid;
    this.type = type;
  }
}
let id = 1000;
onMounted(() => {
  itemCategory()
})
//tree数据
const dataSource = ref([
  // new Tree(1, 'Level one 1', [
  //   new Tree(4, 'Level two 1-1')
  // ]),
  // new Tree(2, 'Level one 2', [
  //   new Tree(5, 'Level two 2-1'),
  //   new Tree(6, 'Level two 2-2')
  // ]),
]);
//请求tree的真实数据
const oneclass = reactive([]) //一级
const otherclass=reactive([])//二级
const itemCategory = async () => {
  dataSource.value.splice(0, dataSource.value.length)
  oneclass.splice(0,oneclass.length)
  otherclass.splice(0, otherclass.length)
  let result = await API.itemCategory()
  if (result.status == 200) {
    // console.log(result.result);
    result.result.forEach(ele => {
      let obj = { id: ele.id, label: ele.name, children: [],cid:ele.cid,type:ele.type }
      if (ele.type == 1) {
        oneclass.push(obj)
      } else {
        otherclass.push(obj)
      }
    })
    oneclass.forEach(item => {
      otherclass.forEach(ele => {
        // console.log(ele);
        if (ele.type === item.cid) {
          item.children.push(ele)
        }
      })
      dataSource.value.push(new Tree(item.id, item.label, item.children,item.cid,item.type))
    })
  }
}
//弹框显示
const centerDialog = ref(null)
// 传给dialog的数据
const title = ref('标题')
const type = ref(1) // 1增加 2修改
const cid = ref('')
const dataid = ref('')
//增加
const append = (data) => {
  // console.log(data);
  centerDialog.value.centerDialogVisible = true
  type.value = 1
  cid.value=data.cid
  title.value = `新增【${data.label}】子类`
  centerDialog.value.input = ''
};
//删除
const remove =(node, data) => {
  ElMessageBox.confirm(
    '此操作将永久删除该文件, 是否继续?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const result = await API.deleteContentCategoryById({ id: data.id })
      // console.log(result);
      if (result.status == 200) {
        itemCategory()
      }
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
};
//修改
const update = (node, data) => {
  // console.log(node, data);
  centerDialog.value.centerDialogVisible = true
  type.value = 2
  dataid.value=data.id
  title.value = `修改【${data.label}】分类名称`
  centerDialog.value.input=data.label
}
//新增一级导航类目
const addoneclass = () => {
  centerDialog.value.centerDialogVisible = true
  title.value = `新增一级导航类目`
  type.value = 3
  centerDialog.value.input = ''
}
//树节点的内容区的渲染
//h就像一个标签，里面是具体内容（标签名、{样式，函数}、渲染的内容）
const renderContent = (h, { node, data, store }) => {
  // console.log('render--',node,data);
  return h(
    'span',
    {
      class: 'custom-tree-node'
    },
    h('span', { class: 'name' }, node.label),
    h(
      'span',
      null,
      node.level === 1 ? [
        h(
          'button',
          {
            style: 'background-color: #409EFF; color: white; border: none; padding: 5px 10px; border-radius: 3px;  cursor: pointer; ', // 默认颜色
            onClick: () => append(data)
          },
          [h(Plus, { style: 'width: 1em; height: 1em; margin-right: 8px' }), '新增 '] // 添加 Plus 图标
        ),
        h(
          'button',
          {
            style: 'background-color: #409EFF; color: white; border: none; padding: 5px 10px; border-radius: 3px;  cursor: pointer; margin :0 20px', // 默认颜色
            onClick: () => update(node, data)
          },
          [h(Edit, { style: 'width: 1em; height: 1em; margin-right: 8px' }), '修改 ']
        ),
        h(
          'button',
          {
            style: 'background-color: #F56C6C; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer;', // danger 颜色
            onClick: () => remove(node, data)
          },
          [h(Delete, { style: 'width: 1em; height: 1em; margin-right: 8px' }), '删除']
        )
      ] : [
        h(
          'button',
          {
            style: 'background-color: #409EFF; color: white; border: none; padding: 5px 10px; border-radius: 3px;  cursor: pointer; margin :0 20px 0 72px', // 默认颜色
            onClick: () => update(node, data)
          },
          [h(Edit, { style: 'width: 1em; height: 1em; margin-right: 8px' }), '修改 ']
        ),
        h(
          'button',
          {
            style: 'background-color: #F56C6C; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer;', // danger 颜色
            onClick: () => remove(node, data)
          },
          [h(Delete, { style: 'width: 1em; height: 1em; margin-right: 8px' }), '删除']
        )
      ]
    )
  );
};
</script>

<style lang="less" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.category {
  margin: 10px;
}

.wrapper {
  padding: 10px;
  margin-top: 10px;
  background: #fff;

  .title {
    background: #f6f6f6;
    height: 50px;
    line-height: 50px;
    font-weight: bold;
    padding-left: 10px;
  }

  .tree {
    margin: 10px;


    :deep(.mini) {
      padding: 4px 10px;
      font-size: 14px;
    }

    :deep(.el-tree-node__content) {
      margin-bottom: 10px;
    }
  }

  :deep(.name) {
    width: 300px;
    display: inline-block;
  }
}
:deep(.el-tree-node.is-expanded.is-focusable ){
  width: 900px;
}
</style>